<template>
  <div class="scores-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="学号">
          <el-input v-model="searchForm.studentId" placeholder="请输入学号" clearable />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="课程">
          <el-select v-model="searchForm.courseId" placeholder="请选择课程" clearable>
            <el-option
              v-for="item in courseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        录入成绩
      </el-button>
      <el-button type="success" @click="handleImport">
        <el-icon><Upload /></el-icon>
        批量导入
      </el-button>
      <el-button type="warning" @click="handleExport">
        <el-icon><Download /></el-icon>
        导出成绩
      </el-button>
    </div>

    <!-- 成绩列表 -->
    <el-table
      v-loading="loading"
      :data="scoreList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="studentId" label="学号" width="120" align="center" />
      <el-table-column prop="studentName" label="姓名" width="120" align="center" />
      <el-table-column prop="className" label="班级" width="120" align="center" />
      <el-table-column prop="courseName" label="课程" width="150" align="center" />
      <el-table-column prop="score" label="分数" width="100" align="center">
        <template #default="{ row }">
          <span :class="getScoreClass(row.score)">{{ row.score }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="examTime" label="考试时间" width="180" align="center" />
      <el-table-column prop="remark" label="备注" min-width="200" align="center" />
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑成绩对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '录入成绩' : '编辑成绩'"
      width="500px"
    >
      <el-form
        ref="scoreFormRef"
        :model="scoreForm"
        :rules="scoreRules"
        label-width="80px"
      >
        <el-form-item label="学生" prop="studentId">
          <el-select
            v-model="scoreForm.studentId"
            filterable
            placeholder="请选择学生"
            @change="handleStudentChange"
          >
            <el-option
              v-for="item in studentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="scoreForm.courseId" placeholder="请选择课程">
            <el-option
              v-for="item in courseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input-number v-model="scoreForm.score" :min="0" :max="100" :precision="1" />
        </el-form-item>
        <el-form-item label="考试时间" prop="examTime">
          <el-date-picker
            v-model="scoreForm.examTime"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="scoreForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  studentId: '',
  name: '',
  courseId: ''
})

// 分页参数
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)

// 成绩列表数据
const scoreList = ref([
  {
    id: 1,
    studentId: '20240001',
    studentName: '张三',
    className: '计算机2024级1班',
    courseName: '高等数学',
    score: 85,
    examTime: '2024-06-15',
    remark: ''
  },
  {
    id: 2,
    studentId: '20240002',
    studentName: '李四',
    className: '计算机2024级1班',
    courseName: '高等数学',
    score: 92,
    examTime: '2024-06-15',
    remark: ''
  },
  {
    id: 3,
    studentId: '20240003',
    studentName: '王五',
    className: '计算机2024级2班',
    courseName: '高等数学',
    score: 78,
    examTime: '2024-06-15',
    remark: ''
  },
  {
    id: 4,
    studentId: '20240001',
    studentName: '张三',
    className: '计算机2024级1班',
    courseName: '大学英语',
    score: 88,
    examTime: '2024-06-18',
    remark: ''
  },
  {
    id: 5,
    studentId: '20240002',
    studentName: '李四',
    className: '计算机2024级1班',
    courseName: '大学英语',
    score: 76,
    examTime: '2024-06-18',
    remark: ''
  }
])

// 课程选项
const courseOptions = [
  { value: '1', label: '高等数学' },
  { value: '2', label: '大学英语' },
  { value: '3', label: '计算机基础' },
  { value: '4', label: '数据结构' },
  { value: '5', label: '操作系统' }
]

// 学生选项
const studentOptions = [
  { value: '20240001', label: '20240001 - 张三 (计算机2024级1班)' },
  { value: '20240002', label: '20240002 - 李四 (计算机2024级1班)' },
  { value: '20240003', label: '20240003 - 王五 (计算机2024级2班)' },
  { value: '20240004', label: '20240004 - 赵六 (计算机2024级2班)' }
]

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const scoreFormRef = ref(null)
const scoreForm = reactive({
  studentId: '',
  courseId: '',
  score: 0,
  examTime: '',
  remark: ''
})

// 表单验证规则
const scoreRules = {
  studentId: [
    { required: true, message: '请选择学生', trigger: 'change' }
  ],
  courseId: [
    { required: true, message: '请选择课程', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入分数', trigger: 'blur' }
  ],
  examTime: [
    { required: true, message: '请选择考试时间', trigger: 'change' }
  ]
}

// 获取成绩列表
const getList = async () => {
  loading.value = true
  try {
    // 模拟API请求
    setTimeout(() => {
      // 模拟筛选
      let filteredList = [...scoreList.value]
      
      if (searchForm.studentId) {
        filteredList = filteredList.filter(item => 
          item.studentId.includes(searchForm.studentId)
        )
      }
      
      if (searchForm.name) {
        filteredList = filteredList.filter(item => 
          item.studentName.includes(searchForm.name)
        )
      }
      
      if (searchForm.courseId) {
        const courseName = courseOptions.find(
          item => item.value === searchForm.courseId
        )?.label
        filteredList = filteredList.filter(item => 
          item.courseName === courseName
        )
      }
      
      total.value = filteredList.length
      
      // 模拟分页
      const start = (page.value - 1) * pageSize.value
      const end = start + pageSize.value
      scoreList.value = filteredList.slice(start, end)
      
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取成绩列表失败:', error)
    ElMessage.error('获取成绩列表失败')
    loading.value = false
  }
}

// 根据分数获取样式类
const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

// 搜索
const handleSearch = () => {
  page.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  page.value = val
  getList()
}

// 添加成绩
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.keys(scoreForm).forEach(key => {
    scoreForm[key] = ''
  })
  scoreForm.score = 0
}

// 编辑成绩
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  
  // 找到对应的课程ID
  const course = courseOptions.find(item => item.label === row.courseName)
  
  scoreForm.id = row.id
  scoreForm.studentId = row.studentId
  scoreForm.courseId = course ? course.value : ''
  scoreForm.score = row.score
  scoreForm.examTime = row.examTime
  scoreForm.remark = row.remark
}

// 学生选择变化
const handleStudentChange = (studentId) => {
  // 实际应用中可以根据学生ID获取学生信息
  console.log('选择的学生ID:', studentId)
}

// 提交表单
const handleSubmit = async () => {
  if (!scoreFormRef.value) return
  
  try {
    await scoreFormRef.value.validate()
    
    // 模拟API请求
    setTimeout(() => {
      // 获取学生信息
      const student = studentOptions.find(item => item.value === scoreForm.studentId)
      const studentInfo = student ? student.label.split(' - ') : []
      const studentName = studentInfo[1] ? studentInfo[1].split(' (')[0] : ''
      const className = studentInfo[1] ? studentInfo[1].match(/\((.*?)\)/)[1] : ''
      
      // 获取课程名称
      const courseName = courseOptions.find(item => item.value === scoreForm.courseId)?.label || ''
      
      if (dialogType.value === 'add') {
        // 模拟添加
        const newScore = {
          id: Date.now(),
          studentId: scoreForm.studentId,
          studentName,
          className,
          courseName,
          score: scoreForm.score,
          examTime: scoreForm.examTime,
          remark: scoreForm.remark
        }
        scoreList.value.unshift(newScore)
        ElMessage.success('添加成功')
      } else {
        // 模拟更新
        const index = scoreList.value.findIndex(item => item.id === scoreForm.id)
        if (index !== -1) {
          scoreList.value[index] = {
            ...scoreList.value[index],
            score: scoreForm.score,
            examTime: scoreForm.examTime,
            remark: scoreForm.remark
          }
        }
        ElMessage.success('更新成功')
      }
      
      dialogVisible.value = false
      getList()
    }, 500)
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

// 删除成绩
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除${row.studentName}的${row.courseName}成绩记录吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除
    const index = scoreList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      scoreList.value.splice(index, 1)
      ElMessage.success('删除成功')
      getList()
    }
  })
}

// 导入成绩
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

// 导出成绩
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.scores-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-toolbar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.score-excellent {
  color: #67C23A;
  font-weight: bold;
}

.score-good {
  color: #409EFF;
  font-weight: bold;
}

.score-pass {
  color: #E6A23C;
}

.score-fail {
  color: #F56C6C;
  font-weight: bold;
}
</style> 